package top.fangw.tenant.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import top.fangw.common.core.constant.BaseConstant;
import top.fangw.common.core.exception.BizException;
import top.fangw.tenant.pojo.dto.DatabasePageQueryDto;
import top.fangw.tenant.pojo.entity.DatabaseInfo;
import top.fangw.tenant.mapper.DatabaseInfoMapper;
import top.fangw.tenant.service.IDatabaseInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.fangw.common.mybatis.annotation.DyDataSource;

/**
 * <p>
 * 用途：保存系统中业务数据库的信息，用于创建租户数据库使用 服务实现类
 * </p>
 *
 * @author fangw
 * @since 2024-01-16
 */
@Service
public class DatabaseInfoServiceImpl extends ServiceImpl<DatabaseInfoMapper, DatabaseInfo> implements IDatabaseInfoService {

    @Override
    @DyDataSource
    public void add(DatabaseInfo databaseInfo) {
        Long count = this.baseMapper.selectCount(new LambdaQueryWrapper<DatabaseInfo>().eq(DatabaseInfo::getName, databaseInfo.getName()));
        if(count > 0){
            throw new BizException("数据库信息已存在！");
        }
        this.baseMapper.insert(databaseInfo);
    }

    @Override
    public void updateInfo(DatabaseInfo databaseInfo) {
        this.baseMapper.updateById(databaseInfo);
    }

    @Override
    public void delete(String id) {
        DatabaseInfo databaseInfo = this.baseMapper.selectById(id);
        if(BaseConstant.CAN_NOT_DELETE.equals(databaseInfo.getIsDeletable())){
            throw new BizException("该数据库信息不可删除");
        }
        this.baseMapper.deleteById(id);
    }

    @Override
    public DatabaseInfo queryById(String id) {
        return this.baseMapper.selectById(id);
    }

    @Override
    public IPage<DatabaseInfo> listPage(DatabasePageQueryDto databasePageQueryDto) {
        IPage<DatabaseInfo> page = new Page<>(databasePageQueryDto.getCurrent(), databasePageQueryDto.getSize());
        QueryWrapper<DatabaseInfo> queryWrapper = new QueryWrapper<>();
        if(StrUtil.isNotBlank(databasePageQueryDto.getName())){
            queryWrapper.like("name", databasePageQueryDto.getName());
        }
        return this.baseMapper.selectPage(page, queryWrapper);
    }
}
